package com.wwwarehouse.taskcenter.fragment.job_point.step2.parent;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.fragment.CommonBasePagerFragment;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.taskcenter.R;
import com.wwwarehouse.taskcenter.bean.job_point.BusinessInfoResponseBean;
import com.wwwarehouse.taskcenter.constant.TaskCenterConstant;
import com.wwwarehouse.taskcenter.constant.job_point.TaskCenterCommon;
import com.wwwarehouse.taskcenter.eventbus_event.JobPointStateEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by Jackie on 2017/10/27
 * 父作业点使用权维度  选择添加方式  选择业务单位添加
 */

public class ChooseAddWayParentUseRightByBusinessFragment extends CommonBasePagerFragment {

    // 搜索排序相关条件
    private String mName = null;
    private String mSort = "create_time desc";

    private int mSelectedPosition = 2;

    private ArrayList<BusinessInfoResponseBean.BusinessDetailsBean> mBusinessDetailsList;

    private static final int REQUEST_GET_BUSINESS_INFO = 0;

    public static final String KEY_SEARCH_BY_NAME = "key_search_by_name";
    public static final String KEY_SEARCH_BY_SORT = "key_search_by_sort";

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initData();
        initEvent();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        ((BaseCardDeskActivity) mActivity).showFilterBt();

        EventBus.getDefault().unregister(this);
    }

    private void initView() {
        mBusinessDetailsList = new ArrayList<>();
    }

    private void initData() {

    }

    private void initEvent() {
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDownPull() {
        if (TaskCenterCommon.getInstance().isDetails()) {

        } else {
            super.onDownPull();

            ((BaseCardDeskActivity) mActivity).hideFilterBt();
        }
    }

    @Override
    public void textNoRealChanged(String text) {
        if (TaskCenterCommon.getInstance().isDetails()) {

        } else {
            if (peekFragment() instanceof ChooseAddWayParentUseRightByBusinessFragment) {
                mName = text;

                // 搜索
                getBusinessInfo(mName, mSort);
            }
        }
    }

    @Override
    public void cancelClick() {
        if (TaskCenterCommon.getInstance().isDetails()) {

        } else {
            if (peekFragment() instanceof ChooseAddWayParentUseRightByBusinessFragment) {
                mName = null;
                mSort = null;

                getBusinessInfo(mName, mSort);
            }
        }
    }

    @Override
    public void sortClick(View anchor) {
        if (TaskCenterCommon.getInstance().isDetails()) {

        } else {
            if (peekFragment() instanceof ChooseAddWayParentUseRightByBusinessFragment) {
                PopUpUtils.showBubbleInviteSort(mActivity, anchor, mSelectedPosition, new PopUpUtils.OnChoiceListener() {
                    @Override
                    public void onChoice(int position) {
                        mSelectedPosition = position;

                        switch (position) {
                            case 2:
                                mSort = "create_time desc";
                                break;
                            case 3:
                                mSort = "create_time asc";
                                break;
                            default:
                                break;
                        }

                        getBusinessInfo(mName, mSort);
                    }
                }, null, getString(R.string.sort_create_time_from_near_to_far), getString(R.string.sort_create_time_from_far_to_near));
            }
        }
    }

    @Override
    public void onRefreshListener() {
        if (TaskCenterCommon.getInstance().isDetails()) {

        } else {
            getBusinessInfo(mName, mSort);
        }
    }

    @Override
    public void onLoadSuccess(String data, int what) {
        switch (what) {
            case REQUEST_GET_BUSINESS_INFO:
                BusinessInfoResponseBean businessInfoResponseBean = JSON.parseObject(data, BusinessInfoResponseBean.class);
                ArrayList<BusinessInfoResponseBean.BusinessDetailsBean> businessDetailsList = (ArrayList<BusinessInfoResponseBean.BusinessDetailsBean>) businessInfoResponseBean.getList();

                try {
                    Bundle bundle = new Bundle();
                    bundle.putString(KEY_SEARCH_BY_NAME, mName);
                    bundle.putString(KEY_SEARCH_BY_SORT, mSort);
                    setData(businessInfoResponseBean.getTotal(), 10, new ChooseAddWayParentUseRightByBusinessDetailsFragment().getClass().getName(), bundle, businessDetailsList);

                    if (businessInfoResponseBean.getTotal() > 0) {
                        initConfirmBtn();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onLoadError(String s) {
        toast(s);
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof ChooseAddWayParentUseRightByBusinessFragment) {
            if (TaskCenterCommon.getInstance().isDetails()) {
                mActivity.setTitle(R.string.view_details);
            } else {
                if (TaskCenterCommon.getInstance().isStart()) {
                    mActivity.setTitle(R.string.choose_start_value);
                } else {
                    mActivity.setTitle(R.string.choose_end_value);
                }
            }
        }
    }

    @Override
    public void requestDatas() {
        super.requestDatas();

        if (TaskCenterCommon.getInstance().isDetails()) {
            //详情页面
            if (TaskCenterCommon.getInstance().isStart()) {
                for (TaskCenterCommon.TaskCenterBean taskCenterBean : TaskCenterCommon.getInstance().parseStartMap()) {
                    BusinessInfoResponseBean.BusinessDetailsBean businessDetailsBean = new BusinessInfoResponseBean.BusinessDetailsBean();
                    businessDetailsBean.setBusinessUnitId(taskCenterBean.getKey());
                    businessDetailsBean.setBusinessUnitName(taskCenterBean.getValue());
                    businessDetailsBean.setSelect(true);
                    mBusinessDetailsList.add(businessDetailsBean);
                }
            } else {
                for (TaskCenterCommon.TaskCenterBean taskCenterBean : TaskCenterCommon.getInstance().parseEndMap()) {
                    BusinessInfoResponseBean.BusinessDetailsBean businessDetailsBean = new BusinessInfoResponseBean.BusinessDetailsBean();
                    businessDetailsBean.setBusinessUnitId(taskCenterBean.getKey());
                    businessDetailsBean.setBusinessUnitName(taskCenterBean.getValue());
                    businessDetailsBean.setSelect(true);
                    mBusinessDetailsList.add(businessDetailsBean);
                }
            }

            try {
                Bundle bundle = new Bundle();
                bundle.putString(KEY_SEARCH_BY_NAME, mName);
                bundle.putString(KEY_SEARCH_BY_SORT, mSort);
                setData(mBusinessDetailsList.size(), 10, new ChooseAddWayParentUseRightByBusinessDetailsFragment().getClass().getName(), bundle, mBusinessDetailsList);

                //有结果才显示确定按钮
                if (mBusinessDetailsList.size() > 0) {
                    initConfirmBtn();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            getBusinessInfo(mName, mSort);
        }
    }

    public void onEventMainThread(JobPointStateEvent event) {
        if (peekFragment() instanceof ChooseAddWayParentUseRightByBusinessFragment) {
            if (TaskCenterCommon.getInstance().isDetails()) {
                for (BusinessInfoResponseBean.BusinessDetailsBean businessDetailsBean : mBusinessDetailsList) {
                    if (businessDetailsBean.isSelect()) {
                        mConfirmBtn.setEnabled(true);

                        return;
                    }
                }

                mConfirmBtn.setEnabled(false);
            } else {
                if (event.getSelectObject() instanceof BusinessInfoResponseBean.BusinessDetailsBean) {
                    BusinessInfoResponseBean.BusinessDetailsBean businessDetailsBean = (BusinessInfoResponseBean.BusinessDetailsBean) event.getSelectObject();

                    if (businessDetailsBean.isSelect()) {
                        mBusinessDetailsList.add(businessDetailsBean);
                    } else {
                        mBusinessDetailsList.remove(businessDetailsBean);
                    }
                }

                if (mBusinessDetailsList.size() > 0) {
                    mConfirmBtn.setEnabled(true);
                } else {
                    mConfirmBtn.setEnabled(false);
                }
            }
        }
    }

    /**
     * 查询四权 业务单位
     */
    private void getBusinessInfo(String name, String sort) {
        Map map = new HashMap();

        map.put("name", name);

        Map queryMap = new HashMap();
        queryMap.put("page", 1);
        queryMap.put("size", 10);
        queryMap.put("sort", sort);

        map.put("query", queryMap);

        loadData(TaskCenterConstant.URL_GET_BUSINESS_INFO, map, REQUEST_GET_BUSINESS_INFO);
    }

    private void initConfirmBtn() {
        showConfirmButton();

        if (TaskCenterCommon.getInstance().isDetails()) {
            mConfirmBtn.setEnabled(true);
        } else {
            mConfirmBtn.setEnabled(false);
        }

        setConfirmBtnText(mActivity.getString(R.string.confirm));

        mConfirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TaskCenterCommon.getInstance().isDetails()) {
                    popFragment();
                } else {
                    popFragment();
                    popFragment();
                }

                buildBusinessMap(mBusinessDetailsList);

                //反向传值
                Intent intent = new Intent("ChooseAddWayParentUseRightByBusiness");
                mActivity.sendBroadcast(intent);
            }
        });
    }

    private void buildBusinessMap(List<BusinessInfoResponseBean.BusinessDetailsBean> businessDetailsList) {
        Map startMap = new HashMap();
        List<Map<String, String>> startList = new ArrayList<>();

        for (BusinessInfoResponseBean.BusinessDetailsBean businessDetailsBean : businessDetailsList) {
            if (businessDetailsBean.isSelect()) {
                Map<String, String> startListMap = new HashMap<>();

                startListMap.put("key", businessDetailsBean.getBusinessUnitId());
                startListMap.put("value", businessDetailsBean.getBusinessUnitName());

                startList.add(startListMap);
            }
        }

        startMap.put("list", startList);
        startMap.put("type", "ITEM");

        TaskCenterCommon.getInstance().setStartMap(startMap);

        Map endMap = new HashMap();
        List<Map<String, String>> endList = new ArrayList<>();
        Map<String, String> endListMap = new HashMap<>();

        endListMap.put("key", "-10002");
        endListMap.put("value", "任意");

        endList.add(endListMap);

        endMap.put("list", endList);
        endMap.put("type", "CONSTANT");

        TaskCenterCommon.getInstance().setEndMap(endMap);
    }
}
